package dxunderground.utilities.io;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import dxunderground.TestData.Employee;

public class ObjSerialization {
	public static void main(String[] args) {
		ObjSerialization.write(new Employee("joe", 12, 134f), "C:/test");
		ObjSerialization.read("C:/test");
	}

	public static List<Object> read(String location) {
		return ObjSerialization.read(new File(location));
	}

	public static List<Object> read(File location) {
		ObjectInputStream ois = null;
		ArrayList<Object> list = new ArrayList<Object>();

		try {
			FileInputStream fis = new FileInputStream(location);

			ois = new ObjectInputStream(fis);

			// available method does not always work correctly
			while (true) {
				Object obj = ois.readObject();
				list.add(obj);
			}

		} catch (EOFException ex) {
			// do nothing in here - expected situation
		} catch (ClassNotFoundException ex) {
			System.out.println(ex);
		} catch (IOException ex) {
			// catches FileNotFoundException here as well
			System.out.println(ex);
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		return list;
	}

	public static void write(Object obj, String location) {
		ObjSerialization.write(obj, new File(location));
	}

	public static void write(Object obj, File location) {
		ObjectOutputStream objOut = null;
		try {
			FileOutputStream fos = new FileOutputStream(location);
			objOut = new ObjectOutputStream(fos);

			objOut.writeObject(obj);
		} catch (NotSerializableException ex) {
			System.out.println(ex);
		} catch (IOException ex) {
			System.out.println(ex);
		} finally {
			if (objOut != null) {
				try {
					objOut.close();
				} catch (IOException ex) {
					System.out.println(ex);
				}
			}
		}
	}
}